package com.ben.utils.util;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public final class AppUtils {

    @SuppressLint("StaticFieldLeak")
    private static Application sApp;
    private static Method cATMtd, gAMtd = null;
    private static WeakReference<Application> ctx = null;

    public static void init(Application application) {
        sApp = application;
    }

    /**
     * Return the Application object.
     *
     * @return the Application object
     */
    public static Application getApp() {
        if (null != sApp) return sApp;
        // reflect application
        Application app;
        if (null != ctx && null != (app = ctx.get())) {
            return app;
        }
        try {
            if (null == cATMtd || null == gAMtd) {
                @SuppressLint("PrivateApi")
                Class<?> aTCls = Class.forName("android.app.ActivityThread");
                cATMtd = aTCls.getMethod("currentActivityThread", (Class<?>) null);
                gAMtd = aTCls.getMethod("getApplication", (Class<?>[]) null);
            }
            app = (Application) gAMtd.invoke(cATMtd.invoke(null, (Object[]) null), (Object[]) null);
            ctx = new WeakReference<>(app);
            return app;
        } catch (Exception ignore) {
            return null;
        }
    }

    public static void hideSystemUI(View view) {
        if (WindowManager.LayoutParams.FLAG_FULLSCREEN == 0 || Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return;
        int WINDOW_FLAGS =
                (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | 0x00002000);
        view.setSystemUiVisibility(WINDOW_FLAGS);
        view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int paramAnonymousInt) {
                if ((paramAnonymousInt & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0) {
                    return;
                }
                view.setSystemUiVisibility(WINDOW_FLAGS);
            }
        });
    }

    public static void killApp() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
